<template>
  <div class="userList">
    <!-- 顶部搜索表单 -->
    <el-form :inline="true">
      <div>
        <el-form-item>
          <el-input
            :clearable="true"
            v-model="searchValue"
            @change="searchAccount"
            placeholder="输入账号进行搜索"
            :prefix-icon="Search"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-select
            @change="searchDepartment"
            v-model="department"
            style="width: 220px"
            placeholder="选择部门进行筛选"
          >
            <el-option
              v-for="item in Department"
              :key="item"
              :value="item"
              :label="item"
            ></el-option>
          </el-select>
        </el-form-item>
      </div>
      <div>
        <el-form-item style="text-align: right">
          <el-button type="primary" size="default" @click="getBanList">筛选冻结用户</el-button>
        </el-form-item>
        <el-form-item style="text-align: right">
          <el-button type="primary" size="default" @click="getUserList" plain
            >显示全部用户</el-button
          >
        </el-form-item>
      </div>
    </el-form>
    <!-- 主体表格 -->
    <el-table :data="UserList" :border="true" @row-dblclick="openDialog">
      <el-table-column align="center" type="index" width="55" />
      <el-table-column
        min-width="90"
        type="default"
        align="center"
        prop="account"
        label="账号"
        width="180"
      />
      <el-table-column min-width="110" type="default" align="center" prop="name" label="姓名" />
      <el-table-column min-width="60" type="default" align="center" prop="sex" label="性别" />
      <el-table-column min-width="90" type="default" align="center" prop="identity" label="身份" />
      <el-table-column
        min-width="90"
        type="default"
        align="center"
        prop="department"
        label="部门"
      />
      <el-table-column
        min-width="90"
        type="default"
        align="center"
        prop="email"
        label="邮箱"
        width="200"
      />
      <el-table-column min-width="90" type="default" align="center" prop="status" label="状态">
        <template v-slot="{ row }">
          <el-tag type="success" v-if="row.status === 1">正常</el-tag>
          <el-tag type="danger" v-else>冻结</el-tag>
        </template>
      </el-table-column>
      <el-table-column type="default" prop="create_time" min-width="200" label="创建时间">
        <template v-slot="{ row }">
          {{ formaDate(row.create_time) }}
        </template>
      </el-table-column>
      <el-table-column type="default" label="操作" min-width="200">
        <template v-slot="{ row }">
          <el-popconfirm
            :title="`你确定要将 ${row.name} 冻结吗`"
            confirm-button-text="确认"
            cancel-button-text="取消"
            @confirm="banUser(row)"
            width="250px"
          >
            <template #reference>
              <el-button type="primary" size="default">冻结</el-button>
            </template>
          </el-popconfirm>
          <el-button type="success" size="default" @click="UnfreezeUser(row)">解冻</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="page"
        :page-size="10"
        layout="prev, pager, next, jumper,total"
        :total="total"
      />
    </div>
  </div>
  <!-- 用户信息弹窗 -->
  <el-dialog center title="用户信息" width="30%" v-model="InfoDialog">
    <el-container>
      <el-aside style="text-align: center; flex: 1.5">
        <el-avatar shape="square" :size="100" :src="userInfo?.image_url"></el-avatar>
      </el-aside>
      <el-main style="text-align: left; flex: 2">
        <div>账号：{{ userInfo?.account }}</div>
        <div>姓名：{{ userInfo?.name }}</div>
        <div>性别：{{ userInfo?.sex }}</div>
        <div>部门：{{ userInfo?.department }}</div>
        <div>邮箱：{{ userInfo?.email }}</div>
        <div>
          状态：
          <span v-if="userInfo?.status === 1">正常</span>
          <span v-else>冻结</span>
        </div>
      </el-main>
    </el-container>
    <el-footer>
      <span @click="editUser">编辑</span>
      <span @click="identityDialog = true" v-if="userInfo1.identity === '超级管理员'">赋权</span>
      <el-popconfirm
        title="你确定要将删除该用户吗"
        confirm-button-text="确认"
        cancel-button-text="取消"
        @confirm="deleteUser"
        width="250px"
      >
        <template #reference>
          <span>删除用户</span>
        </template>
      </el-popconfirm>
    </el-footer>
  </el-dialog>
  <!-- 赋权弹窗 -->
  <el-dialog
    @close="close"
    v-if="userInfo1.identity === '超级管理员'"
    title="赋权"
    width="40%"
    v-model="identityDialog"
  >
    <el-radio-group v-model="identity">
      <el-radio label="产品管理员">产品管理员</el-radio>
      <el-radio label="用户管理员">用户管理员</el-radio>
      <el-radio label="消息管理员">消息管理员</el-radio>
    </el-radio-group>
    <template #footer>
      <el-button type="primary" size="default" @click="identityDialog = false">取消</el-button>
      <el-button type="primary" size="default" @click="sumbitIdentity">确认</el-button>
    </template>
  </el-dialog>
  <el-dialog title="编辑" width="30%" v-model="EditUserDialog">
    <el-form ref="addAdminRef" :model="userInfo" class="form">
      <el-form-item label="账号" prop="account">
        <el-input v-model="userInfo.account" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="userInfo.name"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-select v-model="userInfo.sex">
          <el-option value="男" :key="userInfo?.sex" label="男"></el-option>
          <el-option value="女" :key="userInfo?.sex" label="女"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="部门" prop="department">
        <el-select v-model="userInfo.department">
          <el-option v-for="item in Department" :key="item" :value="item" :label="item"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="userInfo.email"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" size="default" @click="submitEdit">确认</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {
  ChangeStatusAPI,
  deleteUserAPI,
  getAdminListAPI,
  getBanListAPI,
  getDepartmentAPI,
  searchDepartmentAndStatusAPI,
  searchDepartmentAPI,
  SearchUserAPI,
  updateAdminAPI,
  updateIdentityAPI
} from '@/api/userAdmin'
import { onMounted, ref, watch } from 'vue'
import moment from 'moment'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { reactive } from 'vue'
import { tracking } from '@/utils/operation'
import { useUserStore } from '@/stores/user'
const userInfo1 = useUserStore().UserInfo
// 分页器数据
const total = ref<number>()
const page = ref<number>(1)

// 获取用户列表
const UserList = ref<AdminInfo[]>([])
const getUserList = async () => {
  const res: any = await getAdminListAPI('用户', page.value)
  // 获取时清空筛选、搜索信息
  SeacchStatus.value = false
  UserList.value = res.data
  total.value = res.total
  department.value = ''
  searchValue.value = null
}
// 处理日期
const formaDate = (date: string) => {
  return moment(date).format('YYYY-MM-DD HH:mm:ss')
}
// 筛选冻结用户
const SeacchStatus = ref<boolean>(false)
const getBanList = async () => {
  if (department.value) {
    SeacchStatus.value = true
    const res: any = await searchDepartmentAndStatusAPI(page.value, department.value)
    UserList.value = res.data
    total.value = res.total
    return
  }
  SeacchStatus.value = true
  const res: any = await getBanListAPI(page.value)
  UserList.value = res.data
  total.value = res.total
}
// 冻结用户回调
const banUser = async (row: AdminInfo) => {
  await ChangeStatusAPI(0, row.id)
  ElMessage({ type: 'success', message: '冻结成功' })
  tracking('用户', userInfo1?.name!, userInfo.name!, '高级', `冻结`)
  row.status = 0
}
// 解冻用户回调
const UnfreezeUser = async (row: AdminInfo) => {
  await ChangeStatusAPI(1, row.id)
  ElMessage({ type: 'success', message: '解冻成功' })
  /** 记录操作 */
  tracking('用户', userInfo1?.name!, userInfo.name!, '高级', `解冻`)
  row.status = 1
}
// 根据账号搜索
const searchValue = ref<number | null>()
const searchAccount = async () => {
  if (!searchValue.value) {
    getUserList()
    return
  }
  const res = await SearchUserAPI(searchValue.value as number, '用户')
  UserList.value = res.data!
}
// 根据部门筛选
const department = ref<string>('')
const searchDepartment = async () => {
  if (SeacchStatus.value) {
    const res: any = await searchDepartmentAndStatusAPI(page.value, department.value)
    UserList.value = res.data
    total.value = res.total
    return
  }
  const res: any = await searchDepartmentAPI(page.value, department.value)
  UserList.value = res.data
  total.value = res.total
}
// 获取部门列表
const Department = ref<string[]>([])
const getDepartment = async () => {
  const res = await getDepartmentAPI()
  Department.value = JSON.parse(res.data!)
}
// 用户信息详细数据
const userInfo = reactive<UserAdmin>({
  account: null,
  password: '',
  name: '',
  sex: null,
  department: '',
  email: ''
})
// 用户信息弹窗
const InfoDialog = ref<boolean>(false)
const openDialog = (row: UserAdmin) => {
  InfoDialog.value = true
  Object.assign(userInfo, row)
}
// 赋权弹窗
const identityDialog = ref<boolean>(false)
const identity = ref<string>('')
// 赋权弹窗关闭回调
const close = () => {
  identity.value = ''
}
const sumbitIdentity = async () => {
  await updateIdentityAPI(userInfo?.id as number, identity.value)
  identityDialog.value = false
  ElMessage({ type: 'success', message: '添加权限成功' })
  /** 记录操作 */
  tracking('用户', userInfo1?.name!, userInfo.name!, '高级', `赋权`)
  getUserList()
}
// 编辑
const EditUserDialog = ref<boolean>(false)
const editUser = () => {
  EditUserDialog.value = true
}
const submitEdit = async () => {
  await updateAdminAPI(userInfo)
  getUserList()
  EditUserDialog.value = false
  /** 记录操作 */
  tracking('用户', userInfo1?.name!, userInfo.name!, '高级', `编辑`)
  ElMessage({ type: 'success', message: '更新成功' })
}
// 删除用户
const deleteUser = async () => {
  await deleteUserAPI(userInfo.id as number, userInfo.account as number)
  getUserList()
  identityDialog.value = false
  /** 记录操作 */
  tracking('用户', userInfo1?.name!, userInfo.name!, '高级', `删除`)
  ElMessage({ type: 'success', message: '删除成功' })
}
// 监听分页
watch(page, () => {
  if (SeacchStatus.value) {
    getBanList()
    return
  }
  getUserList()
})

onMounted(() => {
  getUserList()
  getDepartment()
})
</script>

<style scoped lang="scss">
.userList {
  padding: 8px;
  .el-form {
    display: flex;
    justify-content: space-between;
    .el-form-item {
      margin: 0;
    }
    .el-form-item:nth-child(2) {
      margin-left: 10px;
    }
  }
  .el-table {
    margin-top: 10px;
    .pagination {
      display: flex;
      justify-content: center;
      margin: 15px;
    }
  }

  .pagination {
    display: flex;
    justify-content: center;
    margin: 15px;
  }
}
.el-aside {
  display: flex;
  align-items: center;
  justify-content: center;
}

.el-footer {
  display: flex;
  justify-content: right;
  align-items: center;
  span {
    margin: 5px;
    cursor: pointer;
    color: rgb(0, 69, 126);
  }
  span:hover {
    color: rgb(4, 119, 213);
  }
}
</style>
